/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *removeZeroSumSublists(ListNode *head)
    {
        vector<int> list;
        while (head != nullptr)
        {
            list.push_back(head->val);
            head = head->next;
        }

        while (true)
        {
            bool deleted = false;
            unordered_map<int, int> prefixSumPosition;
            prefixSumPosition[0] = 0;
            int prefixSum = 0;
            for (int i = 0; i < list.size(); ++i)
            {
                prefixSum += list[i];
                if (prefixSumPosition.count(prefixSum))
                {
                    list.erase(list.begin() + prefixSumPosition[prefixSum], list.begin() + i + 1);
                    deleted = true;
                    break;
                }
                prefixSumPosition[prefixSum] = i + 1;
            }
            if (!deleted)
            {
                break;
            }
        }

        if (list.empty())
        {
            return nullptr;
        }

        ListNode pseudoHead;
        ListNode *cur = &pseudoHead;
        for (int val : list)
        {
            cur->next = new ListNode(val);
            cur = cur->next;
        }
        return pseudoHead.next;
    }
};